using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MauiBuilder.Services;
using System.Collections.ObjectModel;

namespace MauiBuilder.ViewModels
{
    /// <summary>
    /// 消息通知页面的视图模型
    /// 管理通知消息的展示和交互
    /// </summary>
    public partial class NotificationViewModel : BaseViewModel
    {
        private readonly INotificationService _notificationService;
        private readonly LogManager _logManager = LogManager.Instance;
        
        [ObservableProperty]
        private bool _isNotificationRunning = false;
        
        [ObservableProperty]
        private ObservableCollection<NotificationMessage> _notifications = new();
        
        [ObservableProperty]
        private int _unreadCount = 0;
        
        [ObservableProperty]
        private string _lastNotificationTime = "暂无通知";

        public NotificationViewModel(INotificationService notificationService)
        {
            _notificationService = notificationService;
            _logManager.LogInfo("NotificationViewModel 初始化 - 独立通知服务架构");
            
            // 模拟一些初始通知数据
            LoadSampleNotifications();
        }

        #region 计算属性

        /// <summary>
        /// 通知服务状态文本
        /// </summary>
        public string NotificationStatusText => IsNotificationRunning ? "定时通知运行中" : "定时通知已停止";
        
        /// <summary>
        /// 通知服务状态颜色
        /// </summary>
        public Color NotificationStatusColor => IsNotificationRunning ? Colors.Blue : Colors.Gray;

        /// <summary>
        /// 通知数量文本
        /// </summary>
        public string NotificationCountText => $"共 {Notifications.Count} 条通知";

        /// <summary>
        /// 未读通知文本
        /// </summary>
        public string UnreadCountText => UnreadCount > 0 ? $"{UnreadCount} 条未读" : "已全部已读";

        #endregion

        #region 命令

        /// <summary>
        /// 启动通知服务命令
        /// </summary>
        [RelayCommand]
        private async Task OnStartNotification()
        {
            try
            {
                if (!_notificationService.IsNotificationSupported())
                {
                    await AppShell.DisplayAlertAsync(
                        "不支持通知", 
                        "当前平台不支持通知功能");
                    return;
                }

                var hasPermission = await  _notificationService.CheckNotificationPermissionAsync();
                if (!hasPermission)
                {
                    await AppShell.DisplayAlertAsync(
                        "权限不足", 
                        "请授权应用发送通知");
                    return;
                }

                await _notificationService.StartTimedNotificationAsync(
                    "定时通知", 
                    "这是来自通知服务的定时消息", 
                    5);
                    
                IsNotificationRunning = true;
                
                // 更新计算属性
                OnPropertyChanged(nameof(NotificationStatusText));
                OnPropertyChanged(nameof(NotificationStatusColor));
                
                await AppShell.DisplayAlertAsync(
                    "通知启动", 
                    "定时通知服务已启动，将每5秒发送一次通知");
                    
                _logManager.LogInfo("用户启动了定时通知服务");
            }
            catch (Exception ex)
            {
                _logManager.LogInfo($"启动通知服务失败: {ex.Message}");
                await AppShell.DisplayAlertAsync("错误", $"启动通知失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 停止通知服务命令
        /// </summary>
        [RelayCommand]
        private async Task OnStopNotification()
        {
            try
            {
                // 检查是否有运行中的通知服务
                if (!IsNotificationRunning)
                {
                    await AppShell.DisplayAlertAsync(
                        "提示", 
                        "当前没有运行中的通知服务");
                    return;
                }

                // 先调用服务的停止方法
                await _notificationService.StopTimedNotificationAsync();
                
                IsNotificationRunning = false;
                
                // 更新计算属性
                OnPropertyChanged(nameof(NotificationStatusText));
                OnPropertyChanged(nameof(NotificationStatusColor));
                
                await AppShell.DisplayAlertAsync(
                    "通知停止", 
                    "定时通知服务已成功停止");
                    
                _logManager.LogInfo("用户停止了定时通知服务");
            }
            catch (Exception ex)
            {
                _logManager.LogError($"停止通知服务失败: {ex.Message}");
                await AppShell.DisplayAlertAsync("错误", $"停止通知失败: {ex.Message}");
                
                // 即使出错也要更新本地状态
                IsNotificationRunning = false;
                OnPropertyChanged(nameof(NotificationStatusText));
                OnPropertyChanged(nameof(NotificationStatusColor));
            }
        }

        /// <summary>
        /// 发送测试通知命令
        /// </summary>
        [RelayCommand]
        private async Task OnSendTestNotification()
        {
            try
            {
                if (!_notificationService.IsNotificationSupported())
                {
                    await AppShell.DisplayAlertAsync(
                        "不支持通知", 
                        "当前平台不支持通知功能");
                    return;
                }

                await _notificationService.SendNotificationAsync(
                    "测试通知", 
                    $"这是一条测试通知消息 - {DateTime.Now:HH:mm:ss}");
                    
                // 添加到本地通知列表
                var testNotification = new NotificationMessage
                {
                    Id = Guid.NewGuid().ToString(),
                    Title = "测试通知",
                    Content = $"手动发送的测试通知 - {DateTime.Now:HH:mm:ss}",
                    Time = DateTime.Now,
                    Type = NotificationType.Info,
                    IsRead = false
                };
                
                Notifications.Insert(0, testNotification);
                UnreadCount++;
                LastNotificationTime = DateTime.Now.ToString("HH:mm:ss");
                
                OnPropertyChanged(nameof(NotificationCountText));
                OnPropertyChanged(nameof(UnreadCountText));
                    
                _logManager.LogInfo("用户发送了测试通知");
            }
            catch (Exception ex)
            {
                await AppShell.DisplayAlertAsync("错误", $"发送测试通知失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 清除所有通知命令
        /// </summary>
        [RelayCommand]
        private async Task OnClearAllNotifications()
        {
            bool confirm = await AppShell.DisplayConfirmAsync(
                "清除通知", 
                "确定要清除所有通知消息吗？");
                
            if (confirm)
            {
                Notifications.Clear();
                UnreadCount = 0;
                LastNotificationTime = "暂无通知";
                
                OnPropertyChanged(nameof(NotificationCountText));
                OnPropertyChanged(nameof(UnreadCountText));
                
                _logManager.LogInfo("用户清除了所有通知消息");
            }
        }

        /// <summary>
        /// 标记所有为已读命令
        /// </summary>
        [RelayCommand]
        private void OnMarkAllAsRead()
        {
            foreach (var notification in Notifications)
            {
                notification.IsRead = true;
            }
            
            UnreadCount = 0;
            OnPropertyChanged(nameof(UnreadCountText));
            
            _logManager.LogInfo("用户标记所有通知为已读");
        }

        /// <summary>
        /// 刷新通知列表命令
        /// </summary>
        [RelayCommand]
        private async Task OnRefreshNotifications()
        {
            try
            {
                // 模拟刷新延迟
                await Task.Delay(1000);
                
                // 更新通知服务状态显示
                OnPropertyChanged(nameof(NotificationStatusText));
                OnPropertyChanged(nameof(NotificationStatusColor));
                
                // 添加一条新的模拟通知（模拟从通知服务获取最新通知）
                var newNotification = new NotificationMessage
                {
                    Id = Guid.NewGuid().ToString(),
                    Title = "同步通知",
                    Content = $"已同步最新通知数据 - {DateTime.Now:HH:mm:ss}",
                    Time = DateTime.Now,
                    Type = NotificationType.Info,
                    IsRead = false
                };
                
                Notifications.Insert(0, newNotification);
                UnreadCount++;
                LastNotificationTime = DateTime.Now.ToString("HH:mm:ss");
                
                OnPropertyChanged(nameof(NotificationCountText));
                OnPropertyChanged(nameof(UnreadCountText));
                
                _logManager.LogInfo("用户刷新了通知列表");
            }
            catch (Exception ex)
            {
                await AppShell.DisplayAlertAsync("错误", $"刷新失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 通知项点击命令
        /// </summary>
        [RelayCommand]
        private async Task OnNotificationTapped(NotificationMessage notification)
        {
            if (notification == null) return;
            
            // 标记为已读
            if (!notification.IsRead)
            {
                notification.IsRead = true;
                UnreadCount = Math.Max(0, UnreadCount - 1);
                OnPropertyChanged(nameof(UnreadCountText));
            }
            
            await AppShell.DisplayAlertAsync(
                notification.Title,
                $"{notification.Content}\n\n发送时间: {notification.Time:yyyy-MM-dd HH:mm:ss}");
                
            _logManager.LogInfo($"用户查看了通知: {notification.Title}");
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 加载示例通知数据
        /// </summary>
        private void LoadSampleNotifications()
        {
            var sampleNotifications = new List<NotificationMessage>
            {
                new()
                {
                    Id = Guid.NewGuid().ToString(),
                    Title = "欢迎使用",
                    Content = "欢迎使用MAUI智能应用！您可以在这里查看所有通知消息。",
                    Time = DateTime.Now.AddMinutes(-30),
                    Type = NotificationType.Success,
                    IsRead = false
                },
                new()
                {
                    Id = Guid.NewGuid().ToString(),
                    Title = "系统提示",
                    Content = "为了获得最佳体验，请确保已授权应用发送通知。",
                    Time = DateTime.Now.AddHours(-2),
                    Type = NotificationType.Warning,
                    IsRead = true
                },
                new()
                {
                    Id = Guid.NewGuid().ToString(),
                    Title = "功能更新",
                    Content = "应用已更新至最新版本，新增了消息通知管理功能。",
                    Time = DateTime.Now.AddDays(-1),
                    Type = NotificationType.Info,
                    IsRead = true
                },
                new()
                {
                    Id = Guid.NewGuid().ToString(),
                    Title = "定时提醒",
                    Content = "这是一条来自前台服务的定时通知消息。",
                    Time = DateTime.Now.AddMinutes(-5),
                    Type = NotificationType.Reminder,
                    IsRead = false
                }
            };
            
            foreach (var notification in sampleNotifications)
            {
                Notifications.Add(notification);
            }
            
            UnreadCount = Notifications.Count(n => !n.IsRead);
            LastNotificationTime = Notifications.OrderByDescending(n => n.Time).FirstOrDefault()?.Time.ToString("HH:mm:ss") ?? "暂无通知";
        }

        #endregion
    }

    /// <summary>
    /// 通知消息模型
    /// </summary>
    public partial class NotificationMessage : ObservableObject
    {
        [ObservableProperty]
        private string _id = string.Empty;
        
        [ObservableProperty]
        private string _title = string.Empty;
        
        [ObservableProperty]
        private string _content = string.Empty;
        
        [ObservableProperty]
        private DateTime _time;
        
        [ObservableProperty]
        private NotificationType _type;
        
        [ObservableProperty]
        private bool _isRead;

        /// <summary>
        /// 通知图标
        /// </summary>
        public string Icon => Type switch
        {
            NotificationType.Success => "✅",
            NotificationType.Warning => "⚠️",
            NotificationType.Error => "❌",
            NotificationType.Info => "ℹ️",
            NotificationType.Reminder => "⏰",
            _ => "📢"
        };

        /// <summary>
        /// 通知颜色
        /// </summary>
        public Color TypeColor => Type switch
        {
            NotificationType.Success => Colors.Green,
            NotificationType.Warning => Colors.Orange,
            NotificationType.Error => Colors.Red,
            NotificationType.Info => Colors.Blue,
            NotificationType.Reminder => Colors.Purple,
            _ => Colors.Gray
        };

        /// <summary>
        /// 时间显示文本
        /// </summary>
        public string TimeText => Time.ToString("MM-dd HH:mm");
    }

    /// <summary>
    /// 通知类型枚举
    /// </summary>
    public enum NotificationType
    {
        Info,
        Success,
        Warning,
        Error,
        Reminder
    }
}